const express = require('express');
const router = express.Router();
const User = require('../schemas/users');
const Category = require('../schemas/category');
const Content = require('../schemas/content')

router.use(function(req, res, next){
  if(!req.userInfo.isAdmin){
    res.send('对不起，只有管理员才有此权限')
    return;
  }
  next();
})

// 首页
router.get('/', function(req, res, next){
  res.render('admin/index', {
    userInfo: req.userInfo
  });
});
// 用户管理
router.get('/user', async function(req, res, next){
  /**
   * take(2): 限制获取的条数
   * skip(2): 忽略数据的条数
   * 每页显示2条
   * 1：1-2 ship:0 -> (当前页-1)*take
   * 2：2-4 ship:2 -> (当前页-1)*take
   */ 
  let page = req.query.page || 1;
  let take = 2;
  let pages = 0;

  // 获取总条数
  let count = await User.count();
  pages = Math.ceil(count / take);

  page = Math.min(page, pages);
  page = Math.max(page, 1);

  // 计算偏移量
  let skip = (page - 1) * take;

  User.findAll({
    limit: take,
    offset: skip
  }).then(function(users){
    res.render('admin/user_index', {
      userInfo: req.userInfo,
      users: users,
      page: page,
      count: count,
      take: take,
      pages: pages,
      url: '/admin/user'
    });
  });
});
// 分类首页
router.get('/category', async function(req, res){
  // 从数据库中读取所有数据
  let page = req.query.page || 1;
  let param = await getPageParam(page, Category);

  let categorys = await Category.findAll({
    limit: param.take,
    offset: param.skip,
    order: [
      ["id", "DESC"]
    ]
  });

  // 渲染页面
  res.render('admin/category_index', {
    categorys: categorys,
    page: param.page,
    count: param.count,
    take: param.take,
    pages: param.pages
  });

  /*
  // 从数据库中读取所有数据
  let userRe = typeorm.getConnection().getRepository(Category);
  let page = req.query.page || 1;
  let take = 3; 
  let pages = 0;

  // 获取总条数
  let count = await userRe.count();
  pages = Math.ceil(count / take);

  page = Math.min(page, pages);
  page = Math.max(page, 1);

  // 计算偏移量
  let skip = (page - 1) * take;

  userRe.find({
    take: take,
    skip: skip,
    order: {
      id: "DESC"
    }
  }).then(function(categorys){
    res.render('admin/category_index', {
      categorys: categorys,
      page: page,
      count: count,
      take: take,
      pages: pages,
      url: '/admin/category'
    });
  });
  */
})
// 添加分类
router.get('/category/add', function(req, res){
  res.render('admin/category_add', {
    userInfo: req.userInfo
  })
})
// 添加的form表单提交接口
router.post('/category/add', async function(req, res){
  // 判断名字是否为空
  const { name } = req.body;
  if(!name){
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '名称不能为空！'
    });
    return;
  }

  // 获取数据库中是否有相同名称的分类
  let curCat = await Category.findOne({
    where: { name: name }
  });

  if(!curCat){
    let result = await Category.create({name: name});
    if(result){
      res.render('admin/success', {
        userInfo: req.userInfo,
        message: '分类添加成功',
        url: '/admin/category'
      });
    }
  }else{
    // 说明数据库已存在该分类名称
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '分类已经存在！'
    });
  }

  /*
  // 从数据库中读取所有数据
  let dbRe = typeorm.getConnection().getRepository(Category);
  // 获取数据库中是否有相同名称的分类
  let curCat = await dbRe.findOne({
    where: { name: name }
  });
  if(!curCat){
    let result = await dbRe.save({name: name});
    console.log(result);
    if(result){
      res.render('admin/success', {
        userInfo: req.userInfo,
        message: '分类添加成功'
      });
    }
  }else{
    // 说明数据库已存在该分类名称
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '分类已经存在！'
    });
  }
  */
})
// 修改接口
router.get('/category/edit', async function(req, res){
  let id = req.query.id || '';

  // 从数据库中获取分类信息
  let curCat = await Category.findOne({
    where: {id: id}
  });
  if(!curCat){
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '分类信息不存在！'
    });
  }else{
    // 存在，渲染一个模板应用
    res.render('admin/category_edit', {
      userInfo: req.userInfo,
      category: curCat
    });
  }
})
// 修改保存接口
router.post('/category/edit', async function(req, res){
  let id = req.query.id || '';
  let { name } = req.body || '';

  // 从数据库中获取分类信息
  let curCat = await Category.findOne({
    where: {id: id}
  });
  if(!curCat){
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '分类信息不存在！'
    });
  }else{
    // 存在，渲染一个模板应用
    if(name == curCat.name){
      res.render('admin/success', {
        userInfo: req.userInfo,
        message: '修改成功',
        url: '/admin/category'
      });
    }else{
      // 查询要修改的分类名称在数据空中是否存在
      let same = await Category.findOne({
        where: {name: name}
      });
      if(same){
        // 说明存在相同的名称
        res.render('admin/error', {
          userInfo: req.userInfo,
          message: '数据库中已存在同名分类'
        });
      }else{
        // 修改数据
        let updateData = Category.update({
          name: name
        },{
          where: {
            id: id
          }
        });
        res.render('admin/success', {
          userInfo: req.userInfo,
          message: '修改成功',
          url: '/admin/category'
        })
      }
    }
  }
})
// 删除操作
router.get('/category/delete', async function(req, res){
  let id = req.query.id || '';

  // 从数据库中查询是否存在
  let curCat = await Category.findOne({
    where: {id: id}
  });
  if(!curCat){
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '分类信息不存在！'
    });
  }else{
    // 说明存在此数据，直接从数据库中删除
    await Category.destroy({
      where: {
        id: id
      }
    });
    res.render('admin/success', {
      userInfo: req.userInfo,
      message: '删除成功',
      url: '/admin/category'
    })
  }
})
// 内容首页
router.get('/content', async function(req, res){
  let page = req.query.page || 1;
  let param = await getPageParam(page, Content);

  // 相当于是预先加载了category
  let contents = await Content.findAll({
    limit: param.take,
    offset: param.skip,
    order: [
      ["id", "DESC"]
    ],
    include: Category
  });
  res.render('admin/content_index', {
    userInfo: req.userInfo,
    contents: contents,
    page: param.page,
    count: param.count,
    take: param.take,
    pages: param.pages
  });
});
// 内容添加
router.get('/content/add', async function(req, res){
  // 获取所有分类数据
  let categorys = await Category.findAll();
  res.render('admin/content_add', {
    userInfo: req.userInfo,
    categorys: categorys
  })
});
// 内容添加的保存接口
router.post('/content/add', async function(req, res){
  let { category, title, description,content } = req.body;

  if (category == '' || title == '' || description == '' || content == '') {
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '输入项不能为空'
    })
    return;
  }

  let curConten = {
    categoryId: Number(category),
    userId: req.userInfo.id,
    title: title,
    description: description,
    content: content
  }
  let resData = await Content.create(curConten);
  res.render('admin/success', {
    userInfo: req.userInfo,
    message: '保存成功！',
    url: '/admin/content'
  })
})
// 内容编辑
router.get('/content/edit', async function(req, res){
  let { id } = req.query;
  let content = await Content.findOne({
    where: { id: id },
    include: Category
  });

  // 获取所有分类数据
  let categorys = await Category.findAll();

  res.render('admin/content_edit', {
    userInfo: req.userInfo,
    categorys: categorys,
    content: content
  })
})
// 内容编辑的提交按钮
router.post('/content/edit', async function(req, res){
  let id = req.query.id || '';
  let { category, title, description,content } = req.body || '';
  // 对输入参数做校验
  if (category == '' || title == '' || description == '' || content == '') {
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '输入项不能为空'
    })
    return;
  }

  // 从数据库中获取分类信息
  let curContent = await Content.findOne({
    where: {id: id}
  });

  if(!curContent){
    res.render('admin/error', {
      userInfo: req.userInfo,
      message: '内容信息不存在！'
    });
  }else{
    let updateData = await Content.update({
      categoryId: Number(category),
      title: title,
      description: description,
      content: content
    },{
      where: {
        id: id
      }
    });
    res.render('admin/success', {
      userInfo: req.userInfo,
      message: '修改成功',
      url: '/admin/content'
    })
  }

})

// 专门用来处理分页逻辑
async function getPageParam(page, Model){
  let take = 3; 
  let pages = 0;

  // 获取总条数
  let count = await Model.count();
  pages = Math.ceil(count / take);

  page = Math.min(page, pages);
  page = Math.max(page, 1);

  // 计算偏移量
  let skip = (page - 1) * take;

  return {
    page: page,
    count: count,
    take: take,
    pages: pages,
    skip: skip
  }
}
module.exports = router;